package com.cgy.utils.redis.client;

import com.cgy.utils.netx.client.INetworkClientLibrary;
import com.cgy.utils.netx.config.ClientConfig;
import com.cgy.utils.redis.RedisHelper;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.JedisPool;

import java.io.InputStream;

/**
 * @author CHTK
 */
public class RedisClient implements INetworkClientLibrary<RedisHelper> {

    private RedisHelper redisHelper;
    private JedisPool jedisPool;

    @Override
    public INetworkClientLibrary<RedisHelper> initial(ClientConfig clientConfig, Object... extConfig) {
        Preconditions.checkArgument(null != clientConfig);
        Preconditions.checkArgument(StringUtils.isNotBlank(clientConfig.getIp()));
        Preconditions.checkArgument(clientConfig.getPort() > 0);
        if(extConfig.length > 0) {
            Object obj = extConfig[0];
            if(obj instanceof GenericObjectPoolConfig) {
                this.redisHelper = RedisHelper.connect((GenericObjectPoolConfig)obj, clientConfig.getIp(), clientConfig.getPort(), clientConfig.getConnectionTimeoutMs());
            } else {
                this.redisHelper = RedisHelper.connect(clientConfig.getIp(), clientConfig.getPort());
            }
        } else {
            this.redisHelper = RedisHelper.connect(clientConfig.getIp(), clientConfig.getPort());
        }
        this.jedisPool = redisHelper.getJedisPool();
        return this;
    }

    @Override
    public INetworkClientLibrary initial(InputStream inputStream) {
        return this;
    }

    @Override
    public INetworkClientLibrary<RedisHelper> connect() throws Exception {
        return this;
    }

    @Override
    public void release() throws Exception {
        this.jedisPool.destroy();
        this.jedisPool = null;
    }

    @Override
    public RedisHelper getClient() throws Exception {
        return redisHelper;
    }
}
